package cn.laoma.thread5.t5_003_Concurrent_Container;

import java.util.Random;
import java.util.concurrent.*;

/**
 * @program: ThreadDemos
 * @description: BlockingQueue是个阻塞队列
 * 1.天然的实现了生产者消费者模式
 * 2.在queue的基础上增加阻塞方法put和take
 * 3.底层用condition实现，更底层用LockSupport.park实现
 * @author: 老马
 * @create: 2021-10-02 16:47
 **/
public class T04_LinkedBlockingQueue {
    //无界的阻塞队列
    static BlockingQueue<String> queue = new LinkedBlockingQueue<String>();



    public static void main(String[] args) {
        //模拟生产者消费者。一个线程生产；5个线程消费
        new Thread(()->{
            for (int i = 0; i < 100; i++) {
                try {
                    queue.put("馒头" + i);
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
        for (int i = 0; i < 5; i++) {
            new Thread(() -> {
                while (true) {
                    try {
                        System.out.println(Thread.currentThread().getName() + "拿到馒头：" + queue.take());
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    }
}
